package com.longge;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-03-16 00:18
 */
public class MinimalExecTime {

    public double minimalExecTime(TreeNode root) {

        if (root == null) return 0;
        double[] res = dfs(root);
        return res[0] -res[1];



    }

    private double[] dfs(TreeNode treeNode) {
        double[] res = new double[2];
        if (treeNode == null) {
            return res;
        }
        double[] left = dfs(treeNode.left);
        double[] right = dfs(treeNode.right);
        double a = left[0], b = left[1], c = right[0], d = right[1];
        res[0] = left[0]+right[0]+treeNode.val;
        if (a>c){
            if ((a-2*b)<c){
                res[1] = (a+c)/2;
            }else {
                res[1] = b+c;
            }
        }else if (a<c){
            if ((c-2*d)<a){
                res[1] = (a+c)/2;
            }else {
                res[1] = d+a;
            }
        }else {
            res[1] = (a+c)/2;
        }
       return res;

    }

    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        treeNode1.left=treeNode2;
        treeNode1.right=treeNode3;
        MinimalExecTime minimalExecTime = new MinimalExecTime();
        double res = minimalExecTime.minimalExecTime(treeNode1);
        System.out.println(res);
    }
}
